package exp2;

public class SLlist {
    public SLlist() {
        size = 0;
        head.next = null;
        last = head.next;
    }

    private int size;
    private Node head = new Node(0);
    private Node last = new Node(0);
    public void pushBack (int val) {
        Node newnode = new Node(val);
        findlast().next = newnode;
        newnode.next = null;
        size++;
    }
    public void pushFront (int val) {
        Node newnode = new Node(val);
        newnode.next = head.next;
        head.next = newnode;
        size++;
    }
    public int last() {
        return findlast().val;
    }
    public int first() {
        return head.next.val;
    }
    public Node findlast () {
        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        return current;
    }
    public int get (int pos) {
        Node current = new Node(0);
        current = head;
        for (int i = 0; i < pos; i++) {
            current = current.next;
        }
        return current.val;
    }
    public Node getNode(int pos) {
        Node current = new Node(0);
        current = head;
        for (int i = 0; i < pos; i++) {
            current = current.next;
        }
        return current;
    }
    public void deletelast () {
        Node current = head;
        last = null;
        size--;
    }
    public int getSize () {
        return size;
    }
    public void reverse () {
        if (size > 2) {
            Node a = head.next, b = a.next, c = b.next;
            for (int i = 0; i < size - 3; i++) {
                b.next = a;
                a = b;
                b = c;
                c = c.next;
            }
            head.next = c;
            c.next = b;
            b.next = a;
        }
    }

    @Override
    public String toString() {
        Node current = head.next;
        StringBuilder temp = new StringBuilder("[");
        if (current != null) {
            temp.append(current.val);
            for (int i = 1; i < size; i++) {
                current = current.next;
                temp.append(',');
                temp.append(current.val);
            }
            temp.append("]");
        } else {
            temp.append("null]");
        }
        return temp.toString();
    }
}
